package com.mall.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.exception.MyException;
import com.mall.model.Address;
import com.mall.model.Cart;
import com.mall.model.User;
import com.mall.service.AddressService;
import com.mall.service.CartService;

@Controller
@RequestMapping("/CartController")
public class CartController {
	@Autowired
	private CartService cartService;
	@Autowired
	private AddressService addressService;

	/**
	 * 获取购物车集合,如果购物车不为空,继续获取地址信息
	 *
	 * @dagewang 2017年9月5日
	 */
	@RequestMapping("/listCartByUser")
	public String listCartByUser(Model model, HttpSession session) throws Exception {
		User user = (User) session.getAttribute("user");
		if (user == null) {
			return "register";
		}
		List<Cart> list = cartService.list(user.getId());
		if (list.size() != 0) {
			List<Address> addlist = addressService.get(null, user.getId());
			if (addlist.size() == 0) {
				model.addAttribute("addresslist", null);
			} else {
				model.addAttribute("addresslist", addlist);
			}
		}
		if(list.size()==0){
			model.addAttribute("clist", null);
		}else{
			model.addAttribute("clist", list);
		}
		return "userCenterCart";
	}

	/**
	 * 添加购物车
	 *
	 * @dagewang 2017年9月5日
	 */
	@RequestMapping(value = "/addCart", method = RequestMethod.POST)
	@ResponseBody
	public void addCart(Cart cart) throws Exception {
		int result = cartService.save(cart);
		if (result == 0) {
			throw new MyException("添加失败!请刷新尝试");
		}
	}

	/**
	 * 根据Id删除购物车
	 *
	 * @dagewang 2017年9月5日
	 */
	@RequestMapping("/delete")
	public @ResponseBody Map<String, Object> delete(Integer id) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		int result = cartService.delete(id);
		map.put("result", result);
		return map;

	}

	public CartService getCartService() {
		return cartService;
	}

	public void setCartService(CartService cartService) {
		this.cartService = cartService;
	}

	public AddressService getAddressService() {
		return addressService;
	}

	public void setAddressService(AddressService addressService) {
		this.addressService = addressService;
	}

}
